package com.shisfish.library.Controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;

import net.sf.json.JSONArray;

import com.shisfish.library.Impl.BookImpl;
import com.shisfish.library.Impl.BookMessageImpl;
import com.shisfish.library.Impl.JournalRecordImpl;
import com.shisfish.library.Model.Book;
import com.shisfish.library.Model.BookMessage;
import com.shisfish.library.Model.JournalRecord;
import com.shisfish.library.Prere.Login;
import com.shisfish.library.Utils.ChangeISBNUtils;
import com.shisfish.library.Utils.JsonValueUtil;
import com.shisfish.library.Utils.StringUtils;
import com.shisfish.library.Utils.FileUpload.FileUploadUtils;
import com.shisfish.library.Utils.FileUpload.FormJsonArrUtil;
import com.shisfish.library.Utils.Global.GlobalVariable;
import com.shisfish.library.Utils.Global.toJsonUtils;
import com.shisfish.library.Utils.PageModel.Page;
import com.shisfish.library.Utils.PageModel.PageUtils;

@Path("journal")
public class JournalController extends GlobalVariable {

	private BookImpl bookImpl = new BookImpl();
	
	private BookMessageImpl bookMessageImpl = new BookMessageImpl();
	
	FileUploadUtils fileUploadUtils = new FileUploadUtils();

	JsonValueUtil jsonValueUtils = new JsonValueUtil();
	
	private JournalRecordImpl journalRecordImpl = new JournalRecordImpl();
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午6:53:16
	 * @Description 通过 isbn 查找期刊信息
	 * @param isbn
	 * @return
	 */
	@GET
	@Path("selectByISBN/{isbn}")
	@Produces("applicaiton/json; charset=utf-8")
	public String selectByISBN(@PathParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = bookImpl.countISBNJ(isbn);
		
		if (count > 0) {
			
			List<Book> books = bookImpl.selectISBNJ(isbn);
			
			globalMap.put(STATUS_CODE, SUCCESS);
			books.get(0).setIsbn13(isbn);
			globalMap.put("obj", books.get(0));
			
		} else {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午10:26:03
	 * @Description 新增一个期刊
	 * @param idadmin
	 * @param request
	 * @return
	 */
	@POST
	@Path("insertAJournal/{idadmin}")
	@Produces("application/json; charset=utf-8")
	public String insertAJournal(@PathParam("idadmin") String idadmin, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
		
			JSONArray customjsArr;
			// 取得所有文件和表单值
			JSONArray jsArr = fileUploadUtils.getRiverWayUpload(request);
			// 取得所有普通表单值
			customjsArr = new FormJsonArrUtil().getFormJsonArr(jsArr, "form");
	
			// 获取form表单数据
			//String code = jsonValueUtils.getValue(customjsArr, "code");
			String isbn = jsonValueUtils.getValue(customjsArr, "isbn");

			isbn = isbn.replaceAll("-", "");
			if (isbn.length() == 13 || isbn.length() == 10) {
				
			
			//int count = bookImpl.countISBNJ(isbn);
			
			String title = jsonValueUtils.getValue(customjsArr, "title");
			String subtitle = jsonValueUtils.getValue(customjsArr, "subtitle");
			String title_foreign = jsonValueUtils.getValue(customjsArr,
					"title_foreign");
			String author = jsonValueUtils.getValue(customjsArr, "author");
			String publisher = jsonValueUtils.getValue(customjsArr, "publisher");
			String pubaddress = jsonValueUtils.getValue(customjsArr, "pubaddress");
			String pubdate = jsonValueUtils.getValue(customjsArr, "pubdate");
			String pages = jsonValueUtils.getValue(customjsArr, "pages");
			String size = jsonValueUtils.getValue(customjsArr, "size");
			String keyword = jsonValueUtils.getValue(customjsArr, "keyword");
			String summary = jsonValueUtils.getValue(customjsArr, "summary");
			String category = jsonValueUtils.getValue(customjsArr, "category");
			String language = jsonValueUtils.getValue(customjsArr, "language");
			String price = jsonValueUtils.getValue(customjsArr, "price");
			String series_name = jsonValueUtils.getValue(customjsArr, "series_name");
			String enclosure = jsonValueUtils.getValue(customjsArr, "enclosure");
			String cn = jsonValueUtils.getValue(customjsArr, "cn");
			int count = bookImpl.countByISBNJYear(isbn, pubdate);
			
			int period = 0;
			String periodStr = jsonValueUtils.getValue(customjsArr, "period");
			if (!periodStr.isEmpty()) {
				period = Integer.parseInt(periodStr);
			}
			
			int journalSize = 1;
			switch(period) {
				case 1:
					journalSize = 12;
					break;
				case 2:
					journalSize = 52;
					break;
				case 3:
					journalSize = 24;
					break;
				case 4:
					journalSize = 6;
					break;
				case 5:
					journalSize = 4;
					break;
				case 6:
					journalSize = 1;
					break;
			}
			
			
			String unit = jsonValueUtils.getValue(customjsArr, "unit");
			String classification = jsonValueUtils.getValue(customjsArr,
					"classification");
			String binding = jsonValueUtils.getValue(customjsArr, "binding");
			String translator = jsonValueUtils.getValue(customjsArr, "translator");
			String isbn10 = jsonValueUtils.getValue(customjsArr, "issn");
			
			
			
			int count1 = bookImpl.countByCategoryTJ(category);
			
			String code = category + "/" + (count1 + 1);
			
			for (int i = 0; i < journalSize; i++) {
				
				String isbn13 = isbn + "_" + (count + i + 1);
				
				String tit = title + " （第" + (count + i + 1) + "期）";
				Book book = new Book(code, isbn10, isbn13, 
						tit, subtitle, title_foreign, 
						author, publisher, pubaddress, 
						pubdate, pages, size, keyword, 
						summary, category, language, 
						price, series_name, enclosure, 
						cn, period+"", unit, classification, 
						binding, translator);
		
				int flag = bookImpl.insertOne(book);
		
				if (flag == 0) {
					globalMap.put(STATUS_CODE, INSERT_WR);
				} else {
					
					// 新增一本书类的时候 添加书的数量信息
					BookMessage bookMessage = new BookMessage(isbn13, 0, 0, 0, 0, 0);
					bookMessageImpl.insertOne(bookMessage);
					
					// 新增期刊签到记录
					JournalRecord journalRecord = new JournalRecord(isbn13, 0, "", "");
					journalRecordImpl.insertOne(journalRecord);
					globalMap.put(STATUS_CODE, SUCCESS);
				}
			}
			} else {
				globalMap.put(STATUS_CODE, ERROR);
				globalMap.put("message", "请输入13位的isbn!");
			}
		}
		else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		return toJsonUtils.map2Json(globalMap);

	}
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午10:28:06
	 * @Description 修改一个期刊
	 * @param idadmin
	 * @param request
	 * @return
	 */
	@POST
	@Path("updateAJournal/{idadmin}")
	@Produces("application/json; charset=utf-8")
	public String updateAJournal(@PathParam("idadmin") String idadmin, @Context HttpServletRequest request) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
		
			JSONArray customjsArr;
			// 取得所有文件和表单值
			JSONArray jsArr = fileUploadUtils.getRiverWayUpload(request);
			// 取得所有普通表单值
			customjsArr = new FormJsonArrUtil().getFormJsonArr(jsArr, "form");
	
			// 获取form表单数据
			String code = jsonValueUtils.getValue(customjsArr, "code");
			String isbn = jsonValueUtils.getValue(customjsArr, "isbn");
	
			String isbn10 = "";
			String isbn13 = "";
			isbn = isbn.replaceAll("-", "");
			if (isbn.length() == 10) {
				isbn10 = isbn;
				isbn13 = isbn + "123";ChangeISBNUtils.getISBN13(isbn);
			} else {
				isbn10 = isbn.substring(0, 10);
				isbn13 = isbn;
			}
	
			String title = jsonValueUtils.getValue(customjsArr, "title");
			String subtitle = jsonValueUtils.getValue(customjsArr, "subtitle");
			String title_foreign = jsonValueUtils.getValue(customjsArr,
					"title_foreign");
			String author = jsonValueUtils.getValue(customjsArr, "author");
			String publisher = jsonValueUtils.getValue(customjsArr, "publisher");
			String pubaddress = jsonValueUtils.getValue(customjsArr, "pubaddress");
			String pubdate = jsonValueUtils.getValue(customjsArr, "pubdate");
			String pages = jsonValueUtils.getValue(customjsArr, "pages");
			String size = jsonValueUtils.getValue(customjsArr, "size");
			String keyword = jsonValueUtils.getValue(customjsArr, "keyword");
			String summary = jsonValueUtils.getValue(customjsArr, "summary");
			String category = jsonValueUtils.getValue(customjsArr, "category");
			String language = jsonValueUtils.getValue(customjsArr, "language");
			String price = jsonValueUtils.getValue(customjsArr, "price");
			String series_name = jsonValueUtils.getValue(customjsArr, "series_name");
			String enclosure = jsonValueUtils.getValue(customjsArr, "enclosure");
			String cn = jsonValueUtils.getValue(customjsArr, "cn");
			String period = jsonValueUtils.getValue(customjsArr, "period");
			String unit = jsonValueUtils.getValue(customjsArr, "unit");
			String classification = jsonValueUtils.getValue(customjsArr,
					"classification");
			String binding = jsonValueUtils.getValue(customjsArr, "binding");
			String translator = jsonValueUtils.getValue(customjsArr, "translator");
	
			Book book = new Book(code, isbn10, isbn13, title, subtitle,
					title_foreign, author, publisher, pubaddress, pubdate, pages,
					size, keyword, summary, category, language, price, series_name,
					enclosure, cn, period, unit, classification, binding,
					translator);
	
			int flag = bookImpl.updateOne(book);
	
			if (flag == 0) {
				globalMap.put(STATUS_CODE, INSERT_WR);
			} else {
				
				/*// 新增一本书类的时候 添加书的数量信息
				BookMessage bookMessage = new BookMessage(isbn13, 0, 0, 0, 0, 0);
				
				bookMessageImpl.insertOne(bookMessage);*/
				
				globalMap.put(STATUS_CODE, SUCCESS);
			}
		}
		else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		return toJsonUtils.map2Json(globalMap);

	}
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午10:29:03
	 * @Description 删除一个期刊
	 * @param idadmin
	 * @param request
	 * @param isbn
	 * @return
	 */
	@POST
	@Path("deleteByISBN/{idadmin}")
	@Produces("application/json; charset=utf-8")
	public String deleteByISBN(@PathParam("idadmin") String idadmin, @Context HttpServletRequest request, @FormParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
			int flag = bookImpl.deleteOneByKey(isbn);
			
			if (flag == 0) {
				globalMap.put(STATUS_CODE, DELETE_WR);
			} else {
				globalMap.put(STATUS_CODE, SUCCESS);
			}
		} else {
			globalMap.put(STATUS_CODE, NOT_LOGGED_IN);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午10:29:19
	 * @Description 查询期刊信息
	 * @param type
	 * @param choose
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("selectByCho/{type}/{choose}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectByCho(@PathParam("type") String type, @PathParam("choose") String choose, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		List<Book> books = new ArrayList<Book>();
		
		Page page = new Page();
		int count = 0;
		switch(type) {
			case "title" : 
				count = bookImpl.countByTitleJ(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByTitleJ(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "author" :
				count = bookImpl.countByAuthorJ(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByAuthorJ(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "category" :
				count = bookImpl.countByCategoryJ(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByCategoryJ(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "isbn" :
				count = bookImpl.countByISBNJ(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByISBN1J(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "publisher" :
				count = bookImpl.countByPublisherJ(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByPublisherJ(choose, page.getBeginIndex(), pageSize);
				}
				break;
			case "issn" :
				count = bookImpl.countByISSN(choose);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectByISSN(choose, page.getBeginIndex(), pageSize);
				}
				break;	
			default :
				List<String> singleString = StringUtils.getSingleString(choose);
				
				count = bookImpl.countFuzzyJ(singleString);
				if(count > 0){
					page = PageUtils.createPage(count, currentPage, pageSize);
					books = bookImpl.selectFuzzyJ(singleString, page.getBeginIndex(), pageSize);
				}
				break;
		}
		
		if (books.size() > 0) {
			globalMap.put("list", books);
			globalMap.put("page", page);
			globalMap.put(STATUS_CODE, SUCCESS);
		} else if (books.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	/**
	 * @author shisfish
	 * @date 2016年3月11日 下午10:30:00
	 * @Description 
	 * @param choose
	 * @param currentPage
	 * @param pageSize
	 * @return
	 */
	@GET
	@Path("selectFuzzy/{choose}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectFuzzy(@PathParam("choose") String choose, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		List<String> singleString = StringUtils.getSingleString(choose);
		
		int count = bookImpl.countFuzzyJ(singleString);
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			
			List<Book> books = bookImpl.selectFuzzyJ(singleString, page.getBeginIndex(), pageSize);
			
			globalMap.put("list", books);
			
			globalMap.put("page", page);
			
			globalMap.put(STATUS_CODE, SUCCESS);
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		}
		else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("selectFuzzyLess/{choose}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectFuzzyLess(@PathParam("choose") String choose, 
			@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		List<String> singleString = StringUtils.getSingleString(choose);
		
		int count = bookImpl.countFuzzy(singleString);
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			
			List<Map<String, Object>> books = bookImpl.selectFuzzyLessJ(singleString, page.getBeginIndex(), pageSize);
			
			if (books.size() > 0) {
				globalMap.put("list", books);
				globalMap.put("page", page);
				globalMap.put(STATUS_CODE, SUCCESS);
			} else if (books.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		}
		else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("allMessageISBN/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String allMessageISBN(@PathParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		List<Book> books =  bookImpl.selectByISBNJ(isbn.replaceAll("-", ""));
		if (books.size() > 0) {
			globalMap.put("list", books);
			globalMap.put(STATUS_CODE, SUCCESS);
		} else if (books.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("selectAllPage/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectAllPage(@PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = bookImpl.countAllJ();
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			List<Book> books = bookImpl.selectAllPageJ(page.getBeginIndex(), pageSize);
			
			if (books.size() > 0) {
				globalMap.put(STATUS_CODE, SUCCESS);
				globalMap.put("page", page);
				globalMap.put("list", books);
			} else if (books.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}

		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("selectByJournalRecord/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String selectByJournalRecord(@PathParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		List<JournalRecord> journalRecords =  journalRecordImpl.selectByISBN(isbn.replaceAll("-", ""));
		if (journalRecords.size() > 0) {
			globalMap.put("list", journalRecords);
			globalMap.put(STATUS_CODE, SUCCESS);
		} else if (journalRecords.size() == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("updateJournalRecord/{idadmin}/{isbn}")
	@Produces("application/json; charset=utf-8")
	public String updateJournalRecord(@PathParam("idadmin") String idadmin, @Context HttpServletRequest request, 
			@PathParam("isbn") String isbn) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		if (Login.isLoginAdmin(idadmin, request)) {
			List<JournalRecord> journalRecords = journalRecordImpl.selectByKey(isbn);
			if (journalRecords.size() > 0) {
				JournalRecord journalRecord = journalRecords.get(0);
				journalRecord.setIsRecord(1);
				int flag = journalRecordImpl.updateOne(journalRecord);
				if (flag == 0) {
					globalMap.put(STATUS_CODE, INSERT_WR);
				} else {
					globalMap.put(STATUS_CODE, SUCCESS);
				}
			} else if (journalRecords.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else {

		}
		
		return toJsonUtils.map2Json(globalMap);
	}
	
	@GET
	@Path("selectNewAddPage/{type}/{currentPage}/{pageSize}")
	@Produces("application/json; charset=utf-8")
	public String selectNewAddPage(@PathParam("type") int type, @PathParam("currentPage") int currentPage, @PathParam("pageSize") int pageSize) {
		Map<String, Object> globalMap = new HashMap<String, Object>();
		
		int count = bookImpl.countNewAddJ(type);
		
		if (count > 0) {
			Page page = PageUtils.createPage(count, currentPage, pageSize);
			List<Book> books = bookImpl.selectNewAddPageJ(type, page.getBeginIndex(), pageSize);
			
			if (books.size() > 0) {
				globalMap.put(STATUS_CODE, SUCCESS);
				globalMap.put("page", page);
				globalMap.put("list", books);
			} else if (books.size() == 0) {
				globalMap.put(STATUS_CODE, SELECT_EMPTY);
			} else {
				globalMap.put(STATUS_CODE, SELECT_WR);
			}
		} else if (count == 0) {
			globalMap.put(STATUS_CODE, SELECT_EMPTY);
		} else {
			globalMap.put(STATUS_CODE, SELECT_WR);
		}

		return toJsonUtils.map2Json(globalMap);
	}
	
}
